package com.sphd.restaurantsystem.activitys.vip;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.InputType;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.sphd.restaurantsystem.R;
import com.sphd.restaurantsystem.activitys.VipJifenShowActivity;
import com.sphd.restaurantsystem.adapters.ConsumeAdapter;
import com.sphd.restaurantsystem.base.BaseActivity;
import com.sphd.restaurantsystem.base.RestaurantUrl;
import com.sphd.restaurantsystem.info.ConsumeInfo;
import com.sphd.restaurantsystem.info.LoginInfo;
import com.sphd.restaurantsystem.info.RestaurantInfo;
import com.sphd.restaurantsystem.info.VipInfo;
import com.sphd.restaurantsystem.presenter.VipMationPresenterImpl;
import com.sphd.restaurantsystem.utils.Constant;
import com.sphd.restaurantsystem.view.VipMationView;
import com.wzh.frame.utils.StringUtils;
import com.wzh.frame.views.RoundImageView;

import org.litepal.crud.DataSupport;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 会员界面
 */
public class VipInfomationActivity extends BaseActivity implements VipMationView {

    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.vip_img)
    RoundImageView vipImg;
    @BindView(R.id.vip_card)
    ImageView vipCard;
    @BindView(R.id.vip_phone)
    ImageView vipPhone;
    @BindView(R.id.card_or_phone)
    TextView cardOrPhone;
    @BindView(R.id.money_textview)
    TextView moneyTextview;
    @BindView(R.id.etickets_num)
    TextView eticketsNum;
    @BindView(R.id.integral_num)
    TextView integralNum;
    @BindView(R.id.my_recy)
    RecyclerView myRecy;
    @BindView(R.id.my_swf)
    SwipeRefreshLayout mySwf;
    Intent intent;
    Bundle bundle;
    VipInfo vipInfo;
    RestaurantInfo restaurantInfo;
    VipMationPresenterImpl vipMationPresenter;
    ConsumeAdapter consumeAdapter;
    LoginInfo loginInfo;
    @BindView(R.id.content_vip_infomation)
    LinearLayout contentVipInfomation;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_vip_infomation);
        ButterKnife.bind(this);
        initView();
        initEvent();
    }

    private void initEvent() {
        toolbar.setNavigationOnClickListener(view -> {
            setResult(0);
            finish();
        });
        mySwf.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                addData();
            }
        });




    }

    private void initView() {
        intent = getIntent();
        bundle = intent.getExtras();
        loginInfo = DataSupport.findLast(LoginInfo.class);
        vipMationPresenter = new VipMationPresenterImpl(this);
        vipInfo = (VipInfo) bundle.getSerializable(Constant.VIPINFO);
        restaurantInfo = (RestaurantInfo) bundle.getSerializable(Constant.RESTAURANTSINFO);
        setTitleBar(toolbar, StringUtils.isEmpty(vipInfo.getMem_name()) ? vipInfo.getMem_phone() : vipInfo.getMem_name());
        setImage(vipImg, vipInfo.getMem_photo());
        cardOrPhone.setText("卡号:" + (StringUtils.isEmpty(vipInfo.getMem_card()) ? "未填写" : vipInfo.getMem_card()) +
                "\n" + "电话:" + vipInfo.getMem_phone());
        initAdapter();
        addData();
    }

    private void initAdapter() {
        setRefresh(mySwf);
        setRecy(myRecy);
        consumeAdapter = new ConsumeAdapter(R.layout.recycler_consume_item, new ArrayList<>(), this);
        myRecy.setAdapter(consumeAdapter);
    }

    private void addData() {
        if (StringUtils.isEmpty(vipInfo.getMem_card())) {
            vipMationPresenter.addData(RestaurantUrl.Httptitle + RestaurantUrl.VipPayInfo +
                    "cgid=" + restaurantInfo.getId() + "&userPhone=" +
                    (StringUtils.isEmpty(vipInfo.getMem_phone()) ? "userPhone" : vipInfo.getMem_phone()));
        } else {
            vipMationPresenter.addData(RestaurantUrl.Httptitle + RestaurantUrl.VipPayInfo +
                    "cgid=" + restaurantInfo.getId() + "&card=" + vipInfo.getMem_card() + "&userPhone=" +
                    (StringUtils.isEmpty(vipInfo.getMem_phone()) ? "userPhone" : vipInfo.getMem_phone()));
        }
    }

    @Override
    public void recRes(double account, int cards, int integral, List<ConsumeInfo> consumeInfos) {
        vipInfo.setMem_account(account);
        vipInfo.setMem_integral(integral);
        moneyTextview.setText("卡包\n￥" + turn(account));
        eticketsNum.setText("电子优惠券\n" + cards + "张");
        integralNum.setText("积分\n" + integral);
        consumeAdapter.setNewData(consumeInfos);
        mySwf.setRefreshing(false);
    }


    @OnClick({R.id.money_textview, R.id.etickets_num, R.id.vip_card, R.id.integral_num, R.id.vip_phone})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.vip_phone:
                callPhone();
                break;

            case R.id.money_textview:
                if (restaurantInfo.isCg_iscz()) {
                    if (isCanDo()) {
                        bundle.putSerializable(Constant.VIPINFO, vipInfo);
                        intent.putExtras(bundle);
                        intent.setClass(context, VipAddmoneyActivity.class);
                        startActivityForResult(intent, 1);
                    } else {
                        toast("只有接单员能编辑卡包");
                    }

                } else {
                    Toast.makeText(context, "请在主页设置充值是否开启", Toast.LENGTH_SHORT).show();
                }

                break;
            case R.id.etickets_num:
                if (restaurantInfo.isCg_isyh()) {
                    if (isCanDo()) {
                        showEditDialog("优惠券数量", 1);
                    } else {
                        toast("只有接单员能添加优惠券");
                    }
                } else {
                    toast("该店暂不支持优惠券");
                }

                break;
            case R.id.integral_num:
                bundle.putSerializable(Constant.VIPINFO, vipInfo);
                intent.putExtras(bundle);
                intent.setClass(context, VipJifenShowActivity.class);
                startActivityForResult(intent, 1);
                break;
            case R.id.vip_card:
                if (isCanDo()) {
                    showEditDialog("请输入会员卡号", 2);
                } else {
                    toast("只有接单员能编辑卡号");
                }
                break;
        }
    }

    private void callPhone() {
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
                context);
        // set dialog message
        alertDialogBuilder
                .setTitle("提示")
                .setMessage("是否给:" + vipInfo.getMem_phone() + "拨打电话")
                .setCancelable(false)
                .setPositiveButton("确定",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {

                                Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + vipInfo.getMem_phone()));
                                if (ActivityCompat.checkSelfPermission(context, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
                                    // TODO: Consider calling
                                    toast("缺少电话权限，请进入设置-应用程序-权限");
                                    return;
                                }
                                startActivity(intent);

                            }
                        })
                .setNegativeButton("取消",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                dialog.cancel();
                            }
                        });

        // create alert dialog
        AlertDialog alertDialog = alertDialogBuilder.create();

        // show it
        alertDialog.show();
    }

    private void showEditDialog(String title, int type) {
        LayoutInflater li = LayoutInflater.from(context);
        View promptsView = li.inflate(R.layout.layout_edittextdialog, null);

        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
                context);

        alertDialogBuilder.setView(promptsView);

        final EditText userInput = (EditText) promptsView
                .findViewById(R.id.input);
        userInput.setHint("");
        userInput.setInputType(InputType.TYPE_CLASS_NUMBER);
        alertDialogBuilder
                .setCancelable(false)
                .setTitle(title)
                .setPositiveButton("确定",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {

                                if (isNumber1(userInput.getText().toString().trim())) {
                                    addEtickets(userInput.getText().toString().trim(), type);
                                } else {
                                    toast("填入数字");
                                }


                            }
                        })
                .setNegativeButton("取消",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                dialog.cancel();
                            }
                        });

        // create alert dialog
        AlertDialog alertDialog = alertDialogBuilder.create();

        // show it
        alertDialog.show();
    }

    private void addEtickets(String trim, int type) {
        if (type == 1) {
            // TODO: 2016/12/7  
            vipMationPresenter.sendEdit(RestaurantUrl.Httptitle + RestaurantUrl.AddVipEtickets + "cgid=" + restaurantInfo.getId()
                    + "&memphone=" + vipInfo.getMem_phone() + "&cgname=" + restaurantInfo.getCg_name() + "&isyh=" + (restaurantInfo.isCg_isyh() ? "1" : "0")
                    + "&number=" + trim + "&card=" + vipInfo.getMem_card());
        } else if (type == 2) {
            if (trim.equals(vipInfo.getMem_phone())) {
                Toast.makeText(context, "卡号和手机号不允许一样", Toast.LENGTH_SHORT).show();
            } else {
                if (trim.length() <= 15) {
                    vipInfo.setMem_card(trim);
                    vipMationPresenter.sendEdit(RestaurantUrl.Httptitle +
                            RestaurantUrl.ChangeVipCard + "card=" + trim + "&cgid=" + vipInfo.getMem_cgid()
                            + "&memphone=" + vipInfo.getMem_phone());

                } else {
                    Toast.makeText(context, "卡号过长", Toast.LENGTH_SHORT).show();
                }
            }
        }


    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 0) {
            addData();
        }
    }

    @Override
    public void recEditRes(int res) {
        if (res == 1) {
            toast("提交成功");
            cardOrPhone.setText("卡号:" + (StringUtils.isEmpty(vipInfo.getMem_card()) ? "未填写" : vipInfo.getMem_card()) +
                    "\n" + "电话:" + vipInfo.getMem_phone());
            addData();
        } else {
            toast("提交失败");
        }
    }

    private boolean isCanDo() {
        if (!isReciver(loginInfo)) {
            if (isSuperManager(loginInfo)) {
                if (!isCg_has_storemanager(restaurantInfo)) {
                    return true;
                }else {
                    return false;
                }
            } else {
                return false;
            }
        } else {
            return true;
        }

    }

    @Override
    public void showLoading() {
        showLoadingDialog();
    }

    @Override
    public void dissLoading() {
        dissLoadingDialog();

    }
}
